
# 配置
BASE_FOLDER = r'D:\\ProgramData\\html\\22\\upload'  # 修改为您的目标文件夹路径
DOWNLOAD_FOLDER = r'D:\\ProgramData\\html\\22\\download'  # 修改为您想要保存的文件夹路径

from flask import Flask, jsonify, request, send_from_directory, send_file
from flask_cors import CORS
import os
import zipfile
import tempfile
import shutil
from pathlib import Path
import subprocess
import platform

app = Flask(__name__)
CORS(app)  # 允许跨域访问

# 配置
BASE_FOLDER = r'D:\\ProgramData\\html\\22\\upload'  # 修改为您的目标文件夹路径
DOWNLOAD_FOLDER = r'D:\\ProgramData\\html\\22\\download'  # 修改为您想要保存的文件夹路径
DEFAULT_EXTRACT_PATH = r'D:\\ProgramData\\html\\22\\download'  # 默认解压路径

@app.route('/api/folders', methods=['GET'])
def get_folders():
    """获取指定文件夹下的所有文件夹列表"""
    try:
        folders = []
        for item in os.listdir(BASE_FOLDER):
            item_path = os.path.join(BASE_FOLDER, item)
            if os.path.isdir(item_path):
                folders.append({
                    'name': item,
                    'path': item_path,
                    'size': get_folder_size(item_path)
                })
        return jsonify({'folders': folders})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/download', methods=['POST'])
def download_folders():
    """下载选中的文件夹"""
    try:
        data = request.json
        selected_folders = data.get('folders', [])
        
        if not selected_folders:
            return jsonify({'error': '没有选择文件夹'}), 400
        
        # 创建临时zip文件
        temp_dir = tempfile.mkdtemp()
        zip_path = os.path.join(temp_dir, 'folders.zip')
        
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for folder_name in selected_folders:
                folder_path = os.path.join(BASE_FOLDER, folder_name)
                if os.path.exists(folder_path):
                    # 添加文件夹及其内容到zip
                    for root, dirs, files in os.walk(folder_path):
                        for file in files:
                            file_path = os.path.join(root, file)
                            arc_path = os.path.relpath(file_path, BASE_FOLDER)
                            zipf.write(file_path, arc_path)
        
        # 发送文件
        return send_file(zip_path, as_attachment=True, download_name='folders.zip')
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        # 清理临时文件
        if 'temp_dir' in locals():
            shutil.rmtree(temp_dir, ignore_errors=True)

@app.route('/api/upload', methods=['POST'])
def upload_file():
    """上传文件到前端电脑的特定文件夹"""
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        # 确保下载文件夹存在
        os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
        
        # 保存文件
        file_path = os.path.join(DOWNLOAD_FOLDER, file.filename)
        file.save(file_path)
        
        # 如果是zip文件且需要自动解压
        if file.filename.lower().endswith('.zip') and request.form.get('auto_extract', 'false') == 'true':
            extract_path = request.form.get('extract_path', DEFAULT_EXTRACT_PATH)
            extract_zip_on_server(file_path, extract_path)
            return jsonify({
                'message': '文件上传并解压成功',
                'path': file_path,
                'extracted_to': extract_path
            })
        
        return jsonify({'message': '文件上传成功', 'path': file_path})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/extract-zip', methods=['POST'])
def extract_zip():
    """解压zip文件到指定路径"""
    try:
        data = request.json
        zip_path = data.get('zip_path')
        extract_path = data.get('extract_path', DEFAULT_EXTRACT_PATH)
        
        if not zip_path or not os.path.exists(zip_path):
            return jsonify({'error': 'ZIP文件不存在'}), 400
        
        # 确保解压路径存在
        os.makedirs(extract_path, exist_ok=True)
        
        # 解压文件
        with zipfile.ZipFile(zip_path, 'r') as zipf:
            zipf.extractall(extract_path)
        
        return jsonify({
            'message': '解压成功',
            'extract_path': extract_path
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def extract_zip_on_server(zip_path, extract_path):
    """在服务器上解压zip文件"""
    try:
        # 确保解压路径存在
        os.makedirs(extract_path, exist_ok=True)
        
        # 解压文件
        with zipfile.ZipFile(zip_path, 'r') as zipf:
            zipf.extractall(extract_path)
        
        return extract_path
    except Exception as e:
        raise Exception(f"解压失败: {str(e)}")

def get_folder_size(folder_path):
    """计算文件夹大小"""
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

@app.route('/api/auto-extract', methods=['POST'])
def auto_extract():
    """自动解压下载的zip文件到默认路径"""
    try:
        data = request.json
        zip_path = data.get('zip_path')
        
        if not zip_path or not os.path.exists(zip_path):
            return jsonify({'error': 'ZIP文件不存在'}), 400
        
        # 默认解压路径
        extract_path = DEFAULT_EXTRACT_PATH
        
        # 确保解压路径存在
        os.makedirs(extract_path, exist_ok=True)
        
        # 解压文件
        with zipfile.ZipFile(zip_path, 'r') as zipf:
            zipf.extractall(extract_path)
        
        return jsonify({
            'message': '自动解压成功',
            'extract_path': extract_path
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    # 确保默认解压路径存在
    os.makedirs(DEFAULT_EXTRACT_PATH, exist_ok=True)
    os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
    
    # 允许外部访问，监听所有网络接口
    app.run(host='0.0.0.0', port=5000, debug=True)